package repository

import (
	"context"
	"fmt"
	"gin-vben-admin/internal/model"
	"gorm.io/gorm"
)

type SysDeptRepository interface {
	GetById(ctx context.Context, id int64) (m *model.SysDept, err error)
	GetListByPid(ctx context.Context, pid int64) (list []*model.SysDept, err error)
	GetCountByPid(ctx context.Context, pid int64) (total int64, err error)
	UpdateIdPath(ctx context.Context, oldS, newS string) error
	Create(ctx context.Context, user *model.SysDept) error
	Update(ctx context.Context, user *model.SysDept, fields ...string) error
	Delete(ctx context.Context, ids ...int64) error
}

func NewSysDeptRepository(r *Repository) SysDeptRepository {
	return &sysDeptRepository{
		Repository: r,
	}
}

type sysDeptRepository struct {
	*Repository
}

func (r *sysDeptRepository) GetById(ctx context.Context, id int64) (m *model.SysDept, err error) {
	err = r.DB(ctx).Where("dept_id = ?", id).First(&m).Error
	return
}

func (r *sysDeptRepository) Create(ctx context.Context, m *model.SysDept) error {
	return r.DB(ctx).Create(m).Error
}

func (r *sysDeptRepository) Update(ctx context.Context, m *model.SysDept, fields ...string) error {
	_db := r.DB(ctx)
	if len(fields) > 0 {
		_db = _db.Select(fields)
	}
	return _db.Updates(m).Error
}

func (r *sysDeptRepository) Delete(ctx context.Context, ids ...int64) error {
	fmt.Println(ids)
	return r.DB(ctx).Delete(&model.SysDept{}, ids).Error
}

func (r *sysDeptRepository) GetCountByPid(ctx context.Context, pid int64) (total int64, err error) {
	err = r.DB(ctx).Model(model.SysDept{}).Where("parent_id = ?", pid).Count(&total).Error
	return
}

func (r *sysDeptRepository) UpdateIdPath(ctx context.Context, oldS, newS string) error {
	return r.DB(ctx).Model(model.SysDept{}).Where("id_path like ?", oldS+"%").
		UpdateColumn("id_path", gorm.Expr("REPLACE(`id_path`, ?, ?)", oldS, newS)).Error
}

func (r *sysDeptRepository) GetListByPid(ctx context.Context, pid int64) (list []*model.SysDept, err error) {
	list = make([]*model.SysDept, 0)
	if pid == 0 {
		err = r.DB(ctx).Order("sort asc").Find(&list).Error
	} else {
		m := model.SysDept{}
		err = r.DB(ctx).Where("dept_id = ?", pid).First(&m).Error
		if err != nil {
			return
		}
		err = r.DB(ctx).Where("id_path like ?", fmt.Sprintf("%s%d/", m.IdPath, m.DeptId)+"%").Order("sort asc").Find(&list).Error
	}
	return
}
